from flask import Flask, render_template
from flask_cors import CORS
from neo4j import GraphDatabase
from openai import OpenAI
from flask_session import Session
from flask_login import LoginManager, login_required
from app.utils.mysql_util import MySQLUtil
from app.models.user import User

from app.services.node_service import NodeService
from app.services.chat_service import ChatService
from app.services.upload_service import UploadService
from app.services.query_service import QueryService
from app.utils.minio_util import MinioUtil  # 修正导入路径
from config.settings import validate_config
from app.services.auth_service import AuthService

def create_app():
    app = Flask(__name__, static_folder='../static', template_folder='../templates')
    CORS(app)
    
    # 配置Session
    app.config['SECRET_KEY'] = 'your-secret-key'  # 请更改为安全的密钥
    app.config['SESSION_TYPE'] = 'filesystem'
    Session(app)
    
    # 初始化Flask-Login
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    
    auth_service = AuthService()
    
    @login_manager.user_loader
    def load_user(user_id):
        return auth_service.get_user_by_id(user_id)
    
    # 主页路由
    @app.route('/', methods=['GET'])
    @login_required
    def index():
        try:
            return render_template('index4.html')
        except Exception as e:
            app.logger.error(f"Error rendering template: {str(e)}")
            return {'message': str(e), 'errcode': 500}, 500

    # 初始化配置
    app.config.from_object('config.settings')
    validate_config()

    # 初始化服务
    app.neo4j_driver = GraphDatabase.driver(
        app.config['NEO4J_URI'],
        auth=(app.config['NEO4J_USER'], app.config['NEO4J_PASSWORD'])
    )
    
    app.openai_client = OpenAI(
        api_key=app.config['OPENAI_API_KEY'],
        base_url=app.config['OPENAI_BASE_URL']
    )
    
    app.minio_util = MinioUtil()

    # 注册服务
    app.node_service = NodeService(app.neo4j_driver)
    app.chat_service = ChatService(app.openai_client)
    app.upload_service = UploadService(app.minio_util)
    app.query_service = QueryService(app.neo4j_driver)

    # 注册路由
    from app.routes import chat, upload, node, query, cultural_item, profile, auth, message
    app.register_blueprint(auth.bp)
    app.register_blueprint(chat.bp)
    app.register_blueprint(upload.bp)
    app.register_blueprint(node.bp)
    app.register_blueprint(query.bp)
    app.register_blueprint(cultural_item.bp)
    app.register_blueprint(profile.bp)
    app.register_blueprint(message.bp)

    # 注册错误处理
    register_error_handlers(app)

    return app

def register_error_handlers(app):
    @app.errorhandler(404)
    def not_found_error(error):
        return {'message': '未找到请求的资源', 'errcode': 404}, 404

    @app.errorhandler(500)
    def internal_error(error):
        return {'message': '服务器内部错误', 'errcode': 500}, 500

    @app.errorhandler(Exception)
    def handle_exception(error):
        return {'message': str(error), 'errcode': 500}, 500